package com.studytest.yiqilaidati.dao;


import com.studytest.yiqilaidati.modle.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public String findByName(String name) {
        String sql = "select password from user where username=?";
        String password = jdbcTemplate.queryForObject(sql, new Object[]{name}, String.class);
        return password;
    }

    public List<User> findAll() {
        String sql = "select * from user";
        List<User> users = jdbcTemplate.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setNid(resultSet.getInt("nid"));
                user.setUserName(resultSet.getString("userName"));
                user.setPassword(resultSet.getString("password"));
                user.setDesp(resultSet.getString("desp"));
                return user;
            }
        });
        System.out.println(users);
        return users;
    }

    public int saveUser(User user) {

        String sql = "insert into user(id,nid,userName,password,desp) values(?,?,?,?,?)";
        int saveId = jdbcTemplate.update(sql, user.getNid(), user.getUserName(), user.getPassword(), user.getDesp());
        return saveId;
    }

    public int updateUser(User user) {
        String sql = "update user set nid=?,userName=?,password=?,desp=? where id=?";
        int update = jdbcTemplate.update(sql, user.getNid(), user.getUserName(), user.getPassword(), user.getDesp(),user.getId());
        return update;
    }
}
